/**
 * 企业点位
 */
import React, { useEffect, useState } from 'react'
import { Style, Stroke, Fill, Text, Circle } from 'ol/style'
import { generatorVectorSource } from '@ysrd/ol5-react-ts/utils'
// import VectorLayer from 'ol/layer/Vector'
import { Layer } from '@ysrd/ol5-react-ts'
import { getHomeEnterpriseList } from '@/api/electricity'
import dayjs from 'dayjs'

export default (props) => {
  const { layers, setLayers } = props
  const [list, setList] = useState([])

  useEffect(() => {
    const loadData = async () => {
      const datatime = dayjs().unix()
      const dataNewtime = dayjs().format('YYYY-MM-DD HH:20:00')
      const databigtime = dayjs(dataNewtime).unix()
      let time
      if (databigtime < datatime) {
        time = dayjs().format('YYYY-MM-DD HH:00:00')
      } else {
        time = dayjs().subtract(1, 'hours').format('YYYY-MM-DD HH:00:00')
      }
      const result = await getHomeEnterpriseList({
        project_id: 225,
        time: time,
        time_type: 1
      })
      setList(result)
    }
    loadData()
  }, [])

  useEffect(() => {
    if (!props.visible && !list.length) return
    const featureSource = generatorVectorSource(list, {
      lng: 'longitude',
      lat: 'latitude'
    })
    setLayers(
      layers.map((item) => {
        if (item.layerId === props.layerId) {
          item.source = featureSource
          item.style = setStyle()
        }
        return item
      })
    )
  }, [props.visible, list])

  const setStyle = () => {
    const changeColor = (o) => {
      switch (o) {
        case 1:
          return 'red'
        case 2:
          return 'orange'
        case 3:
          return 'green'
        case 4:
          return 'gray'

        default:
          break
      }
    }
    return (f) => {
      const o = f.get('obj')
      return new Style({
        image: new Circle({
          radius: 10,
          fill: new Fill({
            color: 'white'
          }),
          stroke: new Stroke({
            // 边缘颜色
            color: changeColor(o.status),
            width: 3
          })
        }),
        text: new Text({
          textAlign: 'center',
          textBaseline: 'middle',
          font: 'normal 12px Verdana',
          text: o.warn_count + '',
          fill: new Fill({ color: changeColor(o.status) }),
          offsetX: 0,
          offsetY: 0,
          rotation: 0
        }),
      })
    }
  }
  return (
    <Layer.VectorLayer
      visible={props.visible}
      source={props.source}
      style={props.style}
      name={props.layerId}
      zIndex={props.zIndex || 2}
    />
  )
}
